#include "dict.h"
using namespace std;

Dict::Dict(const char * dict_path)
{
	cout << "Init dictionary...";
	string s;
	myutil::readFile(dict_path, s);
	boost::algorithm::trim(s);

	vector<string> res;
	myutil::splitString(s.c_str(), res, '\n');

	for(auto p = res.begin(); p != res.end(); p++)
	{
		boost::algorithm::trim(*p);
		if ((*p).size() == 0)
		{
			continue;
		}

		vector<string> tmp;
		myutil::splitString((*p).c_str(), tmp, '\t');
		if (tmp.size() != 2)
		{
			//cout << "dict file error" << endl;
			continue;
		}

		string word = tmp[0];
		boost::algorithm::trim(word);
		string explain = tmp[1];
		tmp.clear();
		myutil::splitString(explain.c_str(), tmp, ';');

		vector<string> explains ;
		auto pos = m_dict.find(word);
		if (m_dict.end() != pos)
		{
			explains = pos->second;
		}

		for (string & ex: tmp)
		{
			boost::algorithm::trim(ex);
			if(ex.size() == 0 || find(explains.begin(), explains.end(), ex) != explains.end())
			{
				continue;
			}

			ex.shrink_to_fit();
			explains.push_back(ex);
		}

		if (explains.size() == 0)
		{
			continue;
		}

		word.shrink_to_fit();
		explains.shrink_to_fit();
		m_dict[word] = explains;
	}
	cout << m_dict.size() << " pair got." << endl;

	for (auto & p: m_dict)
	{
		cout << p.first << ":";
		for (auto & q: p.second)
		{
			cout << q << "-";
		}
		cout << endl;
	}
}

Dict::~Dict()
{}

vector<string> Dict::getExplains(const string & word) const
{
	auto p = m_dict.find(word);
	if (m_dict.end() == p)
	{
		return vector<string>();
	}
	
	return p->second;
}

